package com.cwx.mychat.utils.stringUtils;

import com.cwx.mychat.entity.constant.CodeConstant;
import com.cwx.mychat.entity.enums.UserContactTypeEnum;
import com.cwx.mychat.utils.common.CommonUtil;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;

import java.net.URI;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil {

    public static boolean isEmpty(String str){
        if(null == str || "".equals(str) || "null".equals(str) || "\u0000".equals(str)){
            return true;
        }else if("".equals(str.trim())){
            return true;
        }
        return false;
    }


    public static String getUserId(){
        return UserContactTypeEnum.USER.getPrefix() + getRandomNumber(CodeConstant.INTEGER_11);
    }

    public static String getGroupId(){
        return UserContactTypeEnum.GROUP.getPrefix() + getRandomNumber(CodeConstant.INTEGER_11);
    }

    public static String getRandomNumber(Integer count){
        return RandomStringUtils.random(count, false, true);
    }

    public static String getRandomString(Integer count){
        return RandomStringUtils.random(count, true, true);
    }

    //去除消息中的标签
    public static String cleanHtmlTag(String content){
        if(isEmpty(content)){
            return content;
        }
        content = content.replace("<", "&lt;");
        content = content.replace(">", "&gt;");
        content = content.replace("\"", "&quot;");
        content = content.replace("'", "&#39;");
        content = content.replace("\r\n", "<br />");
        content = content.replace("\n", "<br />");
        return content;
    }
    //去除消息中的标签
    public static String cleanHtmlDayuXiaoyu(String content){
        if(isEmpty(content)){
            return content;
        }
        content = content.replace("<", "&lt;");
        content = content.replace(">", "&gt;");
        return content;
    }


    public static String cleanSlash(String content){
        if(isEmpty(content)){
            return content;
        }
        content = content.replace("\n", "");
        content = content.replace("\r", "");
        content = content.replace("\t", "");
        return content;
    }
    // 计算字符串的 MD5 哈希值
    public static String MD5(String input) {
        try {
            // 创建 MD5 消息摘要实例
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算哈希值
            byte[] messageDigest = md.digest(input.getBytes());

            // 将字节数组转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0'); // 补充前导零
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 algorithm not found", e);
        }
    }

    //获取文件后缀
    public static String getFileSuffix(String fileName){
        if(isEmpty(fileName)){
            return null;
        }
        return fileName.substring(fileName.lastIndexOf("."));
    }

    //获取url的文件名
    public static String getUrlFileName(String url){
        try{
            URI uri = new URI(url);
            String path = uri.getPath();
            // 获取路径部分
            path = path.substring(url.indexOf('/', path.indexOf('/') + 2)); // 获取到第一个斜杠后的内容
            return path.substring(path.indexOf('/') + 1); // 去掉第一个斜杠
        }catch (Exception e){
            throw new RuntimeException("无法获取url的文件名", e);
        }

    }
    //判断是否为邮箱
    public static boolean isEmail(String str) {
        String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
        return str.matches(emailRegex);
    }
    //判断是否为手机号
    public static boolean isPhoneNumber(String phone) {
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
        if (phone.length() != 11) {
            return false;
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone);
            return m.matches();
        }
    }


    // 匹配HTTP/HTTPS/FTP等协议的URL
    private static final String URL_REGEX =
            "\\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]";

    //判断是否匹配
    public static boolean containUrl(String text){
        Pattern pattern = Pattern.compile(URL_REGEX, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(text);
        return matcher.find();
    }

    //用于处理地址字符串
    public static String convertUrlsToLinks(String text) {
        Pattern pattern = Pattern.compile(URL_REGEX, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(text);
        StringBuffer result = new StringBuffer();

        while (matcher.find()) {
            String url = matcher.group();
            matcher.appendReplacement(result,
                    "<a href=\"" + url + "\" target=\"_blank\">" + url + "</a>");
        }
        matcher.appendTail(result);
        return result.toString();
    }


    public static void main(String[] args) {
//        System.out.println(CommonUtil.getChatSessionIdUser(new String[]{"U707041867320056", "G330930481313170"}));
//        System.out.println(CommonUtil.getChatSessionIdUser(new String[]{"U72102331902", "G330930481313170"}));

        String s = convertUrlsToLinks("什么(https://www.baidu.com)");
        System.out.println("什么(https://www.baidu.com)");

    }
}
